import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
// import 'package:vehicle_management/config/HttpUtils.dart';
import 'package:vehicle_management/config/Config.dart';
import 'package:common_utils/common_utils.dart';
import 'package:vehicle_management/utils/TextFieldItem.dart';

class ForgetPassword extends StatefulWidget {
  @override
  _ForgetPasswordState createState() => _ForgetPasswordState();
}

class _ForgetPasswordState extends State<ForgetPassword> {
  //焦点
  FocusNode _focusNodeUserName = new FocusNode();
  FocusNode _focusNodeTelphone = new FocusNode();
  FocusNode _focusNodeIdcard = new FocusNode();
  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _userNameController = new TextEditingController();
  TextEditingController _idCardController = new TextEditingController();
  TextEditingController _telphoneController = new TextEditingController();
  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

//用户名
  var _userName;
  var _telphone;
  var _idCard;
  var _isShowClear = false;

//是否显示输入框尾部的清除按钮

  @override
  void initState() {
    //设置焦点监听
    _focusNodeUserName.addListener(_focusNodeListener);
    _focusNodeTelphone.addListener(_focusNodeListener);
    _focusNodeIdcard.addListener(_focusNodeListener);
    //监听用户名框的输入改变
    _userNameController.addListener(() {
      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userNameController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    _idCardController.addListener(() {
      if (_idCardController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    _telphoneController.addListener(() {
      if (_telphoneController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // 移除焦点监听
    _focusNodeUserName.removeListener(_focusNodeListener);
    _focusNodeTelphone.removeListener(_focusNodeListener);
    _focusNodeIdcard.removeListener(_focusNodeListener);
    _userNameController.dispose();
    _idCardController.dispose();
    _telphoneController.dispose();
    super.dispose();
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodeUserName.hasFocus) {
      // 取消身份证的焦点状态
      _focusNodeTelphone.unfocus();
      _focusNodeIdcard.unfocus();
    }
    if (_focusNodeIdcard.hasFocus) {
      // 取消手机框焦点状态
      _focusNodeUserName.unfocus();
      _focusNodeTelphone.unfocus();
    }
    if (_focusNodeTelphone.hasFocus) {
      // 取消手机框焦点状态
      _focusNodeUserName.unfocus();
      _focusNodeIdcard.unfocus();
    }
  }

  /// 验证用户名

  String validateUserName(value) {
    if (value.isEmpty) {
      return '用户名不能为空!';
    } else
      return null;
  }

  String validateIdCard(value) {
    if (value.isEmpty) {
      return '身份证不能为空!';
    }
    // else if (!RegexUtil.isIDCard18Exact(value)) {
    //   return '请输入正确的身份证号';
    // }
    return null;
  }

  /// 验证手机号
  String validateTelphone(value) {
    if (value.isEmpty) {
      return '手机号不能为空!';
    } else if (!RegexUtil.isMobileExact(value)) {
      return '请输入正确的手机号';
    }
    return null;
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
    // logo 图片区域
    Widget logoImageArea = new Container(
        alignment: Alignment.center,
        // 设置图片为圆形
        child: Text(
          "忘记密码",
          style: TextStyle(
              color: Colors.white,
              fontSize: ScreenUtil().setSp(60),
              fontWeight: FontWeight.bold),
        ));

    //输入文本框区域
    Widget inputTextArea = new Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(55), right: ScreenUtil().setWidth(55)),
      child: new Form(
        key: _formKey,
        child: new Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            /// 用户名
            TextFieldItem(
              controller: _userNameController,
              focusNode: _focusNodeUserName,
              keyboardType: TextInputType.text,
              labelText: "用户名",
              hintText: '请输入用户名',
              prefixIcon: Icon(
                Icons.person,
                color: Colors.white,
              ),
              suffixIcon: (_isShowClear)
                  ? IconButton(
                icon: Icon(
                  Icons.clear,
                  color: Colors.red,
                ),
                onPressed: () {
                  _userNameController.clear();
                },
              )
                  : null,
              validator: validateUserName,
              //保存数据
              onSaved: (value) {
                _userName = value;
              },
            ),
            new SizedBox(
              height: ScreenUtil().setHeight(30),
            ),

            ///身份证号
            TextFieldItem(
              controller: _idCardController,
              focusNode: _focusNodeIdcard,
              keyboardType: TextInputType.number,
              labelText: "身份证号",
              hintText: '请输入身份证号',
              prefixIcon: Icon(
                Icons.perm_contact_calendar,
                color: Colors.white,
              ),
              suffixIcon: (_isShowClear)
                  ? IconButton(
                icon: Icon(
                  Icons.clear,
                  color: Colors.red,
                ),
                onPressed: () {
                  _idCardController.clear();
                },
              )
                  : null,
              //验证身份证号
              validator: validateIdCard,
              //保存数据
              onSaved: (value) {
                _idCard = value;
              },
            ),
            new SizedBox(
              height: ScreenUtil().setHeight(30),
            ),

            /// 手机号
            TextFieldItem(
              controller: _telphoneController,
              focusNode: _focusNodeTelphone,
              keyboardType: TextInputType.number,
              labelText: "手机号",
              hintText: "请输入手机号",
              prefixIcon: Icon(
                Icons.phone_iphone,
                color: Colors.white,
              ),
              suffixIcon: (_isShowClear)
                  ? IconButton(
                icon: Icon(
                  Icons.clear,
                  color: Colors.red,
                ),
                onPressed: () {
                  _telphoneController.clear();
                },
              )
                  : null,
              //验证手机号
              validator: validateTelphone,
              //保存数据
              onSaved: (value) {
                _telphone = value;
              },
            ),
          ],
        ),
      ),
    );

    // 登录按钮区域
    Widget loginButtonArea = new Container(
      margin: EdgeInsets.only(
          left: ScreenUtil().setWidth(55), right: ScreenUtil().setWidth(55)),
      height: 55,
      child: new RaisedButton(
        color: Color(0xffFB5858),
        child: Text(
          "保存",
          style: Theme.of(context).primaryTextTheme.headline,
        ),
        // 设置按钮圆角
        shape:
        RoundedRectangleBorder(borderRadius: BorderRadius.circular(45.0)),
        onPressed: () async {
          //点击登录按钮，解除焦点，回收键盘
          _focusNodeIdcard.unfocus();
          _focusNodeUserName.unfocus();
          _focusNodeTelphone.unfocus();
          if (_formKey.currentState.validate()) {
            print(_formKey.currentState.validate());
            //只有输入通过验证，才会执行这里
            _formKey.currentState.save();
            //todo 登录操作
            FormData formData = FormData.fromMap({
              "username": _userName,
              "telphone": _telphone,
              "idCard": _idCard,
            });
            print(formData);
            var api = '${Config.resetPasswordtUrl}';
            var response = await Dio().post(api, data: formData);
            print(response);
            if (response.data["code"] == 0) {

              Fluttertoast.showToast(
                msg: '${response.data["msg"]}',
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
              );
              print(json.encode(response.data["data"]));
              Navigator.pushNamed(context,
                  '/'); //使用的是“命名导航路由”，具体去哪个界面，看main.dart 对应routeName（'/Home'）的界面;
            } else {
              Fluttertoast.showToast(
                msg: '${response.data["msg"]}',
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
              );
            }
          }
        },
      ),
    );

    return Scaffold(
      appBar: AppBar(
        title: Text('忘记密码'),
      ),

      // 外层添加一个手势，用于点击空白部分，回收键盘
      body: new GestureDetector(
          onTap: () {
            // 点击空白区域，回收键盘
            _focusNodeTelphone.unfocus();
            _focusNodeUserName.unfocus();
            _focusNodeIdcard.unfocus();
          },
          child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                  image: NetworkImage(
                      "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1593176274503&di=9003ad102c989708e09a61f62f6c2dfc&imgtype=0&src=http%3A%2F%2Ft9.baidu.com%2Fit%2Fu%3D2313840380%2C776106152%26fm%3D193"),
                  fit: BoxFit.cover

                ///AssetImage('images/driverBg.png'),
              ),
            ),
            child: new ListView(
              children: <Widget>[
                new SizedBox(
                  height: ScreenUtil().setHeight(100),
                ),
                logoImageArea,
                new SizedBox(
                  height: ScreenUtil().setHeight(60),
                ),
                inputTextArea,
                new SizedBox(
                  height: ScreenUtil().setHeight(60),
                ),
                loginButtonArea,
                new SizedBox(
                  height: ScreenUtil().setHeight(20),
                ),
              ],
            ),
          )),
    );
  }
}
